package com.wsoft.hr.pm.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONObject;
import com.wsoft.constant.CommonConstant;
import com.wsoft.core.service.CommonFreemarkerService;
import com.wsoft.hr.pm.entity.HrPmMemberTemplateEntity;
import com.wsoft.hr.pm.entity.HrPmWarningEntity;
import com.wsoft.hr.pm.enums.WarningTypeEnum;
import com.wsoft.hr.pm.manager.HrPmMemberTemplateManager;
import com.wsoft.hr.pm.manager.HrPmWarningManager;
import com.wsoft.hr.pm.service.IHrPmMemberTemplateScoreService;
import com.wsoft.hr.pm.vo.member.template.score.ScoreHisVO;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 评分偏差预警
 *
 * @Author z001
 * @Date 2025/3/7 14:22
 */
@Service
public class RatingDeviationJob implements Job {

    @Resource
    private HrPmMemberTemplateManager memberTemplateManager;
    @Resource
    private IHrPmMemberTemplateScoreService scoreService;
    @Resource
    private HrPmWarningManager warningManager;
    @Resource
    private CommonFreemarkerService freemarkerService;

    /**
     * 模版code
     */
    private final String FREEMARKER_CODE = "freemarker_code";
    /**
     * 差值
     */
    private final String DIFFERENCE_VALUE = "difference_value";


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail job = jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap = job.getJobDataMap();

        //任务参数
        Object jobParam = jobDataMap.get(CommonConstant.JOB_PARAMS);
        if (ObjUtil.isNull(jobParam)) {
            return;
        }
        JSONObject param = JSONObject.parseObject(jobParam.toString());
        Object freemarkerCode = param.get(FREEMARKER_CODE);
        Object differenceValue = null == param.get(DIFFERENCE_VALUE) ? "10" : param.get(DIFFERENCE_VALUE);
        if (null == freemarkerCode) {
            return;
        }

        //最后一次执行时间
        String lastExecuteTime = null == jobDataMap.get(CommonConstant.LAST_EXECUTE_TIME) ? null : jobDataMap.get(CommonConstant.LAST_EXECUTE_TIME).toString();
        //当前时间
        String nowExecuteTime = null == jobDataMap.get(CommonConstant.NOW_EXECUTE_TIME) ? null : jobDataMap.get(CommonConstant.NOW_EXECUTE_TIME).toString();

        List<HrPmMemberTemplateEntity> warningList = memberTemplateManager.getWarningList(lastExecuteTime, nowExecuteTime);
        if (CollUtil.isEmpty(warningList)) {
            return;
        }
        List<Long> memberTemplateIds = new ArrayList<>();
        for (HrPmMemberTemplateEntity templateEntity : warningList) {
            List<ScoreHisVO> scoreHis = scoreService.getScoreHis(templateEntity.getId());
            boolean b = filterScores(scoreHis, new BigDecimal(differenceValue.toString()));
            if (b) {
                memberTemplateIds.add(templateEntity.getId());
            }
        }

        if (CollUtil.isEmpty(memberTemplateIds)) {
            return;
        }
        List<HrPmWarningEntity> saveList = new ArrayList<>();

        List<HrPmMemberTemplateEntity> list = memberTemplateManager.listByIds(memberTemplateIds);
        for (HrPmMemberTemplateEntity entity : list) {
            HrPmWarningEntity warning = new HrPmWarningEntity();
            warning.setTitle(buildFreemarkerMap(entity,freemarkerCode));
            warning.setType(WarningTypeEnum.RATING_DEVIATION.getType());
            warning.setHrOrgId(entity.getHrOrgId());
            warning.setOpenType("component");
            warning.setOpenPage("");
            saveList.add(warning);
        }
        warningManager.saveBatch(saveList);


    }


    /**
     * 构建freemarker模板
     * @param vo
     * @param freemarkerCode
     * @return
     */
    private String buildFreemarkerMap(HrPmMemberTemplateEntity vo, Object freemarkerCode){
        Map<String,Object> map = new HashMap<>(3);
        map.put("memberName",vo.getMemberName());
        map.put("templateName",vo.getTemplateName());
        //${memberName}${templateName}的最终评分和自评分存在较大差异，请核实情况。
        return freemarkerService.sendTextTemplate(freemarkerCode.toString(), map,true);
    }



    /**
     * 筛选出 step 为 self 和 leader 的 score 差值在正负 differenceValue 区间内的数据
     *
     * @param scoreHisList    ScoreHisVO 列表
     * @param differenceValue 分数差值
     * @return 符合条件的 ScoreHisVO 列表
     */
    public boolean filterScores(List<ScoreHisVO> scoreHisList, BigDecimal differenceValue) {

        // 遍历列表，找到 step 为 self 和 leader 的 score
        BigDecimal selfScore = null;
        BigDecimal leaderScore = null;

        for (ScoreHisVO scoreHis : scoreHisList) {
            if ("self".equals(scoreHis.getStep())) {
                selfScore = scoreHis.getScore();
            } else if ("leader".equals(scoreHis.getStep())) {
                leaderScore = scoreHis.getScore();
            }
        }

        // 如果 selfScore 和 leaderScore 都存在，则计算差值
        if (selfScore != null && leaderScore != null) {
            // 计算绝对差值
            BigDecimal difference = selfScore.subtract(leaderScore).abs();

            // 判断差值是否在正负 differenceValue 区间内
            if (difference.compareTo(differenceValue) <= 0) {
                return true;
            }
        }
        return false;
    }

}
